package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-12-06 00:52
 **/
public class LeetCode1816 {

    //一次遍历
    public String truncateSentence(String s, int k) {
        int size = s.length();
        int end = 0;
        for (int i = 0; i <= size; i++) {
            if (i == size || s.charAt(i) == ' ') {
                k--;
                if (k == 0) {
                    end = i;
                }
            }
        }
        return s.substring(0, end);
    }

    //api调度
    /*public String truncateSentence(String s, int k) {
        String[] strs = s.split(" ");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < k; i++) {
            builder.append(strs[i]).append(" ");
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }*/

}
